package response;

import database.DatabaseHandler;
import database.mysql.ConnectionMySQL;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import json.SimpleJson;


@WebServlet(name = "ResponseTabela", urlPatterns = {"/ResponseTabela"})
public class ResponseTabela extends HttpServlet {

    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/xml");
        response.setHeader("Cache-Control", "no-cache");
                
        DatabaseHandler dbh = new DatabaseHandler(new ConnectionMySQL("observador","observador"));
        String json = "[\"Erro: gerou conjunto vazio\"]";
        
        if(request.getParameterMap().containsKey("teste")){
            response.getWriter().write("[Resposta: "+request.getParameter("teste")+"]");
        }
        
        if(request.getParameterMap().containsKey("request")){
           // String requestReceived = request.getParameter("request");
            String condition = "";
            SimpleJson sj = new SimpleJson();;
            
            String allRequests = request.getParameter("request");
            String[] requestsReceived = allRequests.split(",");
            ArrayList queryList = new ArrayList();
            
            for(int i = 0; i < requestsReceived.length; i++){
                String requestReceived = requestsReceived[i];
                String requestedQuery = "";
                
                if(requestReceived.equals("rodadas")){
                    requestedQuery = "SELECT rodada, id, rodada, hora_planejada, hora_realizada, publico_pagante, renda_total, duracao_t1, duracao_t2, id_estadio, id_clube_casa, id_clube_visitante FROM partida ORDER BY rodada";
                }
                else if(requestReceived.equals("clubes")){
                    requestedQuery = "SELECT * FROM clube ORDER BY nome_resumido";
                }
                else if(requestReceived.equals("gols")){
                    String rodada = request.getParameter("rodada");
                    requestedQuery = "SELECT g.* FROM gol g, partida p WHERE g.id_partida = p.id AND p.rodada = " + rodada + " ORDER BY id_partida";
                }
                else if(requestReceived.equals("jogadores")){
                    requestedQuery = "SELECT * FROM jogador";
                }
                else if(requestReceived.equals("cartoesPartida")){  
                    String partida = request.getParameter("partida");
                    requestedQuery = "SELECT * FROM cartao WHERE id_partida = "+partida;
                }
                else if(requestReceived.equals("substituicoesPartida")){
                    String partida = request.getParameter("partida");
                    requestedQuery = "SELECT * FROM substituicao WHERE id_partida = "+partida;
                }
                else if(requestReceived.equals("tabela")){
                    //response.getWriter().write("TOMAR NO CU");
                    requestedQuery = "SELECT retornarTabela(id) FROM clube";
                }
                else if(requestReceived.equals("data")){
                    //response.getWriter().write("TOMAR NO CU");
                    requestedQuery = "SELECT retornarDataFormatoCorreto(NOW())";
                }
                else if(requestReceived.equals("artilheiros")){
                    requestedQuery = "SELECT COUNT(*) AS numGols, id_jogador FROM gol g GROUP BY id_jogador ORDER BY numGols DESC";
                }
                
                queryList.add(requestedQuery);
            }
            
            for(int i = 0; i<queryList.size(); i++){
                String query = (String) queryList.get(i);
                
                try{ 
                    ResultSet rs = dbh.getResult(query);
                    
                    sj.setResultSet(rs);
                    sj.generate();
                    
                }catch(SQLException e){

                }
                
            }
           
            json = sj.getContent();
            response.getWriter().write(json);
        }
        
        /*
        if(request.getParameterMap().containsKey("call")){
            String object = request.getParameter("call");
            
            try{
                ResultSet rs = dbh.getResult("CALL "+object);
                
                response.getWriter().write("[Mensagem: Chamada "+object+" executada]");
            }catch(SQLException e){
                
            }
        }
        
        if(request.getParameterMap().containsKey("__")){
            String object = request.getParameter("listAll");
            String orderBy = "";
            String condition = "";
            
            if(request.getParameterMap().containsKey("orderBy"))
                orderBy = " ORDER BY "+request.getParameter("orderBy");
            
            //Queba o parametro condition e junta numa string
            if(request.getParameterMap().containsKey("condition")){
                String[] conditionList = request.getParameter("condition").split(",");
                String conditionString = "";
                
                for(int i = 0; i < conditionList.length; i++){
                    String conditionItem = conditionList[i];
                    conditionItem = conditionItem.replace("$$","=");
                    
                    conditionString += conditionItem;
                    if(i > 0) conditionString = " AND " + conditionItem;
                }
                condition = " WHERE " + conditionString;
            }
            
            try{
                ResultSet rs = dbh.getResult("SELECT * FROM "+object+condition+orderBy);
                SimpleJson sj = new SimpleJson(rs);
                sj.generate();
                String json = sj.getContent();
                response.getWriter().write(json);
            }catch(SQLException e){
                
            }
        }*/
    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}